<%- contentFor('heroContent') %>
  <!-- Hero Banner with Search -->
  <div class="hero-banner detail-hero-banner" style="margin-bottom: 30px;">
    <div class="hero-content">
      <h1 class="upload-title">图片上传</h1>
    </div>
  </div>

  <div class="upload-container">
    <h2>上传图片</h2>

    <% if (error) { %>
      <div class="error">
        <%= error %>
      </div>
      <% } %>

        <% if (success) { %>
          <div class="success">
            <%= success %>
          </div>
          <% } %>

            <form action="/upload-images" method="POST" enctype="multipart/form-data" class="upload-form"
              id="uploadForm">
              <div class="form-group">
                <label for="images">选择图片文件 (可多选):</label>
                <input type="file" id="images" name="images" accept="image/*" multiple required>
              </div>

              <div class="form-info">
                <p>支持的格式: .jpg, .jpeg, .png, .gif</p>
                <p>最大文件大小: <strong>1MB</strong> 每张图片</p>
                <p>上传的图片将保存在服务器上，并可用于图书和期刊的封面</p>
              </div>

              <div id="sizeError" class="error" style="display: none;">
                一个或多个图片超过了1MB大小限制，请重新选择小于1MB的图片。
              </div>

              <% if (imageUrls && imageUrls.length> 0) { %>
                <div class="uploaded-images-container">
                  <h3>已上传图片链接</h3>
                  <div class="image-links-wrapper">
                    <% imageUrls.forEach(function(imageUrl) { %>
                      <div class="image-link-item">
                        <div>
                          <%= imageUrl %>
                        </div>
                      </div>
                      <% }); %>
                  </div>
                </div>
                <% } %>

                  <button type="submit" class="upload-btn">上传图片</button>
            </form>


  </div>

  <style>
    .upload-title {
      font-size: 28px;
      color: white;
      margin: 0;
    }

    .uploaded-images-container {
      margin-top: 30px;
      background-color: #f8f9fa;
      padding: 20px;
      border-radius: 8px;
    }

    .uploaded-images-container h3 {
      margin-top: 0;
      margin-bottom: 15px;
      color: #2c3e50;
    }

    .image-links-wrapper {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }

    .image-link-item {
      background: white;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .image-preview {
      width: 100%;
      height: 150px;
      margin-bottom: 10px;
      overflow: hidden;
      border-radius: 4px;
      border: 1px solid #eee;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .image-preview img {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }

    .image-url-container {
      display: flex;
      gap: 10px;
    }

    .image-url-input {
      flex-grow: 1;
      padding: 8px 12px;
      border: 2px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      background-color: #f9f9f9;
      color: #333;
      font-family: monospace;
      transition: all 0.2s ease;
    }

    .image-url-input:hover {
      border-color: #bbb;
    }

    .image-url-input:focus {
      outline: none;
      border-color: #111579;
      background-color: #fff;
      box-shadow: 0 0 0 2px rgba(17, 21, 121, 0.1);
    }

    .copy-btn {
      background-color: #111579;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 8px 12px;
      cursor: pointer;
      font-size: 14px;
      transition: background-color 0.2s;
      min-width: 80px;
    }

    .copy-btn:hover {
      background-color: #0d115f;
    }

    .upload-tip {
      color: #666;
      font-size: 14px;
      margin-bottom: 15px;
      padding: 8px 12px;
      background-color: #f0f8ff;
      border-left: 3px solid #111579;
      border-radius: 3px;
    }

    .error {
      color: #721c24;
      background-color: #f8d7da;
      border: 1px solid #f5c6cb;
      padding: 10px 15px;
      margin-bottom: 15px;
      border-radius: 4px;
    }
  </style>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const copyButtons = document.querySelectorAll('.copy-btn');
      const MAX_FILE_SIZE = 1 * 1024 * 1024; // 1MB in bytes

      // 检查是否支持Clipboard API
      let clipboardSupported = false;
      if (navigator.clipboard) {
        clipboardSupported = true;
      }

      // 备用复制方法
      function fallbackCopyTextToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;

        // 设置样式使其不可见
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = '0';
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';

        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        let success = false;
        try {
          success = document.execCommand('copy');
        } catch (err) {
          console.error('Fallback: 复制出错', err);
        }

        document.body.removeChild(textArea);
        return success;
      }

      copyButtons.forEach(button => {
        button.addEventListener('click', async function () {
          const url = this.dataset.url;
          let success = false;

          try {
            if (clipboardSupported) {
              await navigator.clipboard.writeText(url);
              success = true;
            } else {
              success = fallbackCopyTextToClipboard(url);
            }

            // 显示复制结果
            if (success) {
              const originalText = this.textContent;
              this.textContent = '已复制!';
              this.style.backgroundColor = '#4CAF50';

              setTimeout(() => {
                this.textContent = originalText;
                this.style.backgroundColor = '#111579';
              }, 2000);
            } else {
              this.textContent = '请手动复制';

              setTimeout(() => {
                this.textContent = '复制链接';
              }, 2000);

              // 聚焦并选中输入框中的文本，以便用户手动复制
              const inputField = this.parentNode.querySelector('.image-url-input');
              if (inputField) {
                inputField.focus();
                inputField.select();
              }
            }
          } catch (err) {
            console.error('复制失败:', err);

            // 尝试备用方法
            success = fallbackCopyTextToClipboard(url);

            if (success) {
              const originalText = this.textContent;
              this.textContent = '已复制!';
              this.style.backgroundColor = '#4CAF50';

              setTimeout(() => {
                this.textContent = originalText;
                this.style.backgroundColor = '#111579';
              }, 2000);
            } else {
              this.textContent = '请手动复制';

              setTimeout(() => {
                this.textContent = '复制链接';
              }, 2000);

              // 聚焦并选中输入框中的文本，以便用户手动复制
              const inputField = this.parentNode.querySelector('.image-url-input');
              if (inputField) {
                inputField.focus();
                inputField.select();
              }
            }
          }
        });
      });

      // 自动选择文本的功能
      const urlInputs = document.querySelectorAll('.image-url-input');

      urlInputs.forEach(input => {
        input.addEventListener('click', function () {
          this.select();
        });

        input.addEventListener('focus', function () {
          this.select();
        });
      });

      // 防止刷新页面时重复提交表单
      const fileInput = document.getElementById('images');
      const uploadForm = document.getElementById('uploadForm');
      const sizeError = document.getElementById('sizeError');

      // 文件大小验证
      fileInput.addEventListener('change', function (e) {
        const files = this.files;
        let hasOversizedFiles = false;

        for (let i = 0; i < files.length; i++) {
          if (files[i].size > MAX_FILE_SIZE) {
            hasOversizedFiles = true;
            break;
          }
        }

        if (hasOversizedFiles) {
          sizeError.style.display = 'block';
          this.value = ''; // 清空文件选择
        } else {
          sizeError.style.display = 'none';
        }
      });

      // 表单提交验证
      uploadForm.addEventListener('submit', function (e) {
        const files = fileInput.files;
        let hasOversizedFiles = false;

        for (let i = 0; i < files.length; i++) {
          if (files[i].size > MAX_FILE_SIZE) {
            hasOversizedFiles = true;
            break;
          }
        }

        if (hasOversizedFiles) {
          e.preventDefault();
          sizeError.style.display = 'block';
          return false;
        }

        // 如果有成功提示，说明已经上传过了，在这种情况下为表单添加提交前确认
        const successMessage = document.querySelector('.success');
        if (successMessage && !confirm('你确定要再次上传图片吗？这将创建新的图片链接。')) {
          e.preventDefault();
          return false;
        }
      });

      // 在页面加载时清空文件输入
      if (fileInput) {
        fileInput.value = '';
      }

      // 处理浏览器的前进/后退导航
      window.addEventListener('pageshow', function (event) {
        // 如果页面是从缓存加载的，清空文件输入
        if (event.persisted || (window.performance &&
          window.performance.navigation.type === 2)) {
          if (fileInput) {
            fileInput.value = '';
          }
        }
      });

      // 处理F5刷新
      window.addEventListener('beforeunload', function () {
        // 在页面卸载前将sessionStorage中设置一个标记
        sessionStorage.setItem('pageRefreshed', 'true');
      });

      // 检查是否是刷新操作
      if (sessionStorage.getItem('pageRefreshed') === 'true') {
        // 清除标记
        sessionStorage.removeItem('pageRefreshed');
        // 清空文件输入
        if (fileInput) {
          fileInput.value = '';
        }
      }
    });
  </script>
